package com.ljsw.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.ljsw.activity.ckpage.CKReconcialationActivity;
import com.ljsw.activity.ckpage.CkNotCompletedActivity;
import com.ljsw.adapter.PKListInfoAdapter;
import com.ljsw.application.App;
import com.ljsw.dialog.LoadIngDialog;
import com.ljsw.dialog.TimeOut;
import com.ljsw.entity.gpk.CheckInventory;
import com.ljsw.entity.pkentity.LtOrder;
import com.ljsw.entity.pkentity.PKListinfoEntity;
import com.ljsw.entity.pkentity.PKListinfolistCode;
import com.ljsw.server.UpServer;
import com.ljsw.util.DialogManager;
import com.pkutils.TurnListviewHeight;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

import static com.ljsw.application.App.user;


/****
 * 盘库数据数据显示和用户自己判断是否盘库
 */
public class CKListInfoActivity extends Activity implements View.OnClickListener, Thread.UncaughtExceptionHandler {
    private ListView cklistviewinfo;// listview 组件
    private List<PKListinfoEntity> PKListinfolist = new ArrayList<PKListinfoEntity>();
    private TimePickerView pvTime;
    private TimePickerView pvTimeEnd;

    private WangdianBaseAdapter wa;
    private Button btnstarttask, cktv_selecttimeend, cktv_selecttime;//  开始任务

    private List<Integer> ltCurrent_WD = new ArrayList<Integer>();
    private List<List<Integer>> ltCurrent_Order = new ArrayList<List<Integer>>();// 网点显示状态列表
    private static final String TAG = "PKListInfoActivity";
    private Handler handler;
    private TimeOut timeout;//超时连接
    private DialogManager dmanager;//弹出框管理类
    private String Starttime = "";
    private String Endtime = "";
    private Button btncreatetaskck;//   查库
    List<CheckInventory> listresult = new ArrayList<CheckInventory>();
    private List<Map<String, String>> listmap = new ArrayList<Map<String, String>>();
    private App app;//
    Map<String, String> mapitem = new HashMap<String, String>();
    public String userid;//  操作人

    //    -----------------------
    private List<PKListinfolistCode> PKListinfolistlist = new ArrayList<PKListinfolistCode>();//   外层的集合显示
    private List<PKListinfolistCode> PKListinfolistlist2 = new ArrayList<PKListinfolistCode>();//   外层的集合显示
    private PKListInfoAdapter pPKListInfoAdapter;


    private Button ckbtnselecttask;//   查询任务
    private LoadIngDialog LoadIngDialog;
    private Button ckl_update;
    private ImageView ckblack_;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cklist_info);
        Thread.setDefaultUncaughtExceptionHandler(this);
        PKListinfoEntity pk = new PKListinfoEntity();
        app = (App) this.getApplication();
        InitView();
        wa = new WangdianBaseAdapter(PKListinfolistlist2);
        cklistviewinfo.setAdapter(wa);

        dmanager = new DialogManager(CKListInfoActivity.this);
//        dmanager = new DialogManager(this);
        timeout = dmanager.getTimeOut();//超时弹框
        dmanager = new DialogManager(this);
        LoadIngDialog = dmanager.getLoadIngDialog().builder();

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0://   传时间获取数据成功

                        PKListinfolistlist2.clear();
                        ltCurrent_Order.clear();
                        ltCurrent_WD.clear();
                        Log.d("login用户role------------", user.getUserId());
                        for (int x = 0; x < PKListinfolistlist.size(); x++) {

                            PKListinfolistlist2.add(new PKListinfolistCode(
                                    PKListinfolistlist.get(x).getLtOrder(),
                                    PKListinfolistlist.get(x).getName()));
                        }
                        for (int i = 0; i < PKListinfolistlist2.size(); i++) {
                            List<Integer> ltt = new ArrayList<Integer>();
                            for (int j = 0; j < PKListinfolistlist2.get(i).getLtOrder().size(); j++) {
                                ltt.add(1);
                            }
                            ltCurrent_Order.add(ltt);
                            if (i == 0) {
                                ltCurrent_WD.add(1);
                            } else {
                                ltCurrent_WD.add(0);
                            }
                        }
                        wa.notifyDataSetInvalidated(); // 更新数据
                        LoadIngDialog.dismiss();
                        break;

                    case 2:
                        Toast.makeText(CKListInfoActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                        LoadIngDialog.dismiss();
                        break;

                    case 1://登录
                        Toast.makeText(CKListInfoActivity.this, "请检查网络", Toast.LENGTH_SHORT).show();
                        break;
                    case 4://账户长度是否正确符合要求 用户不存在
                        Toast.makeText(CKListInfoActivity.this, "账户长度不对", Toast.LENGTH_SHORT).show();
                        break;
                    case 5://判断密码的长度密码错误
                        Toast.makeText(CKListInfoActivity.this, "请检查密码", Toast.LENGTH_SHORT).show();
                        break;

                    case 7://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "请检查用户名", Toast.LENGTH_SHORT).show();
                        break;
                    case 8://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "无返回结果", Toast.LENGTH_SHORT).show();
                        break;
                    case 9://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "时间不对", Toast.LENGTH_SHORT).show();
                        break;
                    case 10://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "请检查时间", Toast.LENGTH_SHORT).show();
                        break;
                    case 11://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "任务创建成功", Toast.LENGTH_SHORT).show();
                        SelectTask();
                        wa.notifyDataSetInvalidated(); // 更新数据
                        LoadIngDialog.dismiss();
                        break;
                    case 12://用户不正确
                        Toast.makeText(CKListInfoActivity.this, "" + createresult, Toast.LENGTH_SHORT).show();
                        LoadIngDialog.dismiss();
                        break;

                    default:
                        Toast.makeText(CKListInfoActivity.this, "请检查网络服务", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        };
    }


    @Override
    protected void onResume() {
        super.onResume();
        GetSystemTiem();
        LoadIngDialog.show();
        SelectTask();


    }

    private void GetSystemTiem() {

    }

    /***
     * 获取任务列表
     * <p>
     * app.userZhanghao
     */

    private void InitView() {
        cklistviewinfo = (ListView) findViewById(R.id.cklistviewinfo);
        cktv_selecttime = (Button) findViewById(R.id.cktv_selecttimeitme);
        cktv_selecttime.setOnClickListener(this);
        cktv_selecttimeend = (Button) findViewById(R.id.cktv_selecttimeend);//  显示结束时间
        cktv_selecttimeend.setOnClickListener(this);
        btncreatetaskck = (Button) findViewById(R.id.btncreatetaskck);// 创建任务
        btncreatetaskck.setOnClickListener(this);

        ckbtnselecttask = (Button) findViewById(R.id.ckbtnselecttask);// 查询任务
        ckbtnselecttask.setOnClickListener(this);
        ckl_update = (Button) findViewById(R.id.ckl_update);//   更新
        ckl_update.setOnClickListener(this);
        ckblack_ = (ImageView) findViewById(R.id.ckblack_);
        ckblack_.setOnClickListener(this);

    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        Log.d("getTime()", "choice date millis: " + date.getTime());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cktv_selecttimeitme:
                SelectTime();
                break;
            case R.id.btncreatetaskck://  如果没有任务发起任务
                CreateTaskCK();

                break;
            case R.id.cktv_selecttimeend://  选择结束时间
                EndTime();
                break;
            case R.id.ckbtnselecttask:
                SelectTask();
                break;


            case R.id.ckl_update:// 更新
                SelectTask();

                break;

            case R.id.ckblack_:
                CKListInfoActivity.this.finish();
                break;
            default:
                break;

        }
    }

    /**
     * 查询任务
     */
    private String username;

    private void SelectTask() {
        String orgind = user.getOrganizationId();
        userid = app.userZhanghao;
        username = user.getName();
        Starttime = "";
        Endtime = "";
        Starttime = "" + cktv_selecttime.getText().toString().trim();
        Endtime = "" + cktv_selecttimeend.getText().toString().trim();
        Log.e(TAG, "!!!!!!!!!" + Starttime);
        Log.e(TAG, "!!!!!!Endtime!!!" + Endtime);
        new Thread(new Runnable() {
            public void run() {
                try {
                    if (Starttime.equals("开始时间") || Endtime.equals("结束时间")) {
                        Log.e(TAG, "返回时间====" + System.currentTimeMillis());
                        Starttime = "";
                        Endtime = "";
                        String result = UpServer.inventoryTaskListForCheckInventory(Starttime, Endtime, userid);
                        Log.e(TAG, "!!!!!!!!!!!!!!" + result);
                        Gson gson = new Gson();
                        PKListinfolistCode[] mTailZerotoEntity = gson.fromJson(result, PKListinfolistCode[].class);
                        List arrList = Arrays.asList(mTailZerotoEntity);
                        PKListinfolistlist.clear();
                        PKListinfolistlist = new ArrayList(arrList);
                        for (int i = 0; i < PKListinfolistlist.size(); i++) {
                            if (PKListinfolistlist.get(i).getName().contains("已对账")) {
                                PKListinfolistlist.remove(i);
                            }

                        }
                        if (PKListinfolistlist != null && !PKListinfolistlist.equals("")) {
                            handler.sendEmptyMessage(0);
                        } else {
                            handler.sendEmptyMessage(2);
                            LoadIngDialog.dismiss();
                        }

                    } else {
                        String result = UpServer.inventoryTaskListForCheckInventory(Starttime, Endtime, userid);
                        Log.e(TAG, "返回结果===！！！！！" + result);
                        if (result.equals("") || result == null) {
                            handler.sendEmptyMessage(8);//查无此人信息
                        } else {
                            PKListinfolistlist.clear();//  清空
                            Gson gson = new Gson();
                            PKListinfolistCode[] mTailZerotoEntity = gson.fromJson(result, PKListinfolistCode[].class);
                            List arrList = Arrays.asList(mTailZerotoEntity);//  必须加
                            PKListinfolistlist.clear();
                            PKListinfolistlist = new ArrayList(arrList);
                            for (int i = 0; i < PKListinfolistlist.size(); i++) {
                                if (PKListinfolistlist.get(i).getName().contains("已对账")) {
                                    PKListinfolistlist.remove(i);
                                }

                            }
                            if (PKListinfolistlist != null && !PKListinfolistlist.equals("")) {
                                handler.sendEmptyMessage(0);
                            } else {
                                handler.sendEmptyMessage(2);
                                LoadIngDialog.dismiss();
                            }


                        }
                    }

                } catch (TimeoutException e) {
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(2);

                }
            }
        }).start();

    }

    private void EndTime() {
        pvTimeEnd = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置标题
        pvTimeEnd.setTitle("选择日期");
        //控制时间范围
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

//        pvTime.setRange(calendar.get(Calendar.YEAR) - 90, calendar.get(Calendar.YEAR));


        pvTimeEnd.setTime(new Date());
        //设置是否循环
        pvTimeEnd.setCyclic(false);
        //设置是否可以关闭
        pvTimeEnd.setCancelable(true);
        //设置选择监听
        pvTimeEnd.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                Log.e("MainActivity", "当前选择时间：" + getTime(date));
                cktv_selecttimeend.setText(getTime(date));
            }
        });
        //显示
        pvTimeEnd.show();
    }

    /***
     * 时间选择
     */
    private void SelectTime() {
        pPKListInfoAdapter = new PKListInfoAdapter(PKListinfolist, CKListInfoActivity.this);
        //时间选择器
        pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
        //设置标题
        pvTime.setTitle("选择日期");
        //控制时间范围
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

//        pvTime.setRange(calendar.get(Calendar.YEAR) - 90, calendar.get(Calendar.YEAR));


        pvTime.setTime(new Date());
        //设置是否循环
        pvTime.setCyclic(false);
        //设置是否可以关闭
        pvTime.setCancelable(true);
        //设置选择监听
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                Log.e("MainActivity", "当前选择时间：" + getTime(date));
                cktv_selecttime.setText("" + getTime(date));
            }
        });
        //显示
        pvTime.show();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //在此处理异常， arg1即为捕获到的异常
        Log.e("AAA", "uncaughtException -----  " + ex);
    }

    class WangdianBaseAdapter extends BaseAdapter {
        private List<PKListinfolistCode> PKListinfolistlist2;
        private ViewHolder vh;

        public WangdianBaseAdapter(List<PKListinfolistCode> PKListinfolistlist) {
            super();
            this.PKListinfolistlist2 = PKListinfolistlist;
        }

        @Override
        public int getCount() {
            return PKListinfolistlist2.size();
        }

        @Override
        public Object getItem(int arg0) {
            return PKListinfolistlist2.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(int arg0, View v, ViewGroup arg2) {
            System.out.println("-----wa更新-----");
            final LayoutInflater inflater = LayoutInflater.from(CKListInfoActivity.this);
            if (v == null) {
                v = inflater.inflate(R.layout.item_qingfengrenwu_qingfen_wangdian, null);
                vh = new WangdianBaseAdapter.ViewHolder();
                vh.tvWangdianName = (TextView) v.findViewById(R.id.tv_item_qingfenrenwu_qingling_wangdain_name);
                vh.lvOrderNo = (ListView) v.findViewById(R.id.lv_item_qingfenrenwu_qingling_wangdain_orderNo);
                vh.rlTitle = (RelativeLayout) v.findViewById(R.id.rl_item_qingfenrenwu_qingling_wangdain_title);
                vh.llInfo = (LinearLayout) v.findViewById(R.id.ll_item_qingfenrenwu_qingling_wangdain_order);
                v.setTag(vh);
            } else {
                vh = (ViewHolder) v.getTag();
            }
            // 设置网点名字
            vh.tvWangdianName.setText(PKListinfolistlist2.get(arg0).getName());
            // 遍历计算已选择的订单数量
            int a = 0;// a为过渡使用的变量
            // 显示已选择的订单数量
            vh.rlTitle.setOnClickListener(new CKListInfoActivity.OpenOnClickListener(arg0));// 给网点标题栏添加点击事件
            // 绑定订单列表Adapter
            vh.lvOrderNo.setAdapter(new CKListInfoActivity.WandianOrderBaseAdapter(PKListinfolistlist2.get(arg0).getLtOrder(), arg0));

            vh.lvOrderNo.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                }
            });


            // 根据标识来设置当前选中网点,选中的网点则标识为1.
            if (ltCurrent_WD.get(arg0) == 1) {
                vh.llInfo.setVisibility(View.VISIBLE);
            } else {
                vh.llInfo.setVisibility(View.GONE);
            }
            new TurnListviewHeight(vh.lvOrderNo);
            return v;
        }

        public class ViewHolder {
            //            CheckBox cbAllSelect;// 全选checkbox
            TextView tvWangdianName;// 网点名称
            TextView tvSelectCount;// 已选择订单的数量
            ListView lvOrderNo;// 订单列表
            Button btnOk;// 确定按钮
            RelativeLayout rlTitle;// 网点标题布局
            LinearLayout llInfo;// 网点内容布局
        }
    }

    class OpenOnClickListener implements View.OnClickListener {
        private int positon;

        public OpenOnClickListener(int positon) {
            super();
            this.positon = positon;
        }

        @Override
        public void onClick(View arg0) {
            for (int i = 0; i < ltCurrent_WD.size(); i++) {
                if (i == positon) {
                    ltCurrent_WD.set(i, 1);
                } else {
                    ltCurrent_WD.set(i, 0);
                }
            }
            wa.notifyDataSetChanged();
        }
    }

    class WandianOrderBaseAdapter extends BaseAdapter {
        private List<LtOrder> lt;
        private int position;

        public WandianOrderBaseAdapter(List<LtOrder> lt, int position) {
            super();
            this.lt = lt;
            this.position = position;
        }

        @Override
        public int getCount() {
            System.out.print("!!!!!!!!!!!!" + lt.size());
            return lt.size();
        }

        @Override
        public Object getItem(int arg0) {
            return lt.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            return arg0;
        }

        @Override
        public View getView(final int arg0, View arg1, ViewGroup arg2) {
            LayoutInflater inflater = LayoutInflater.from(CKListInfoActivity.this);
            View v = inflater.inflate(R.layout.item_qingfenrenwu_qiangling_wangdian_orderno, null);
            TextView smtext = (TextView) v.findViewById(R.id.smtext);
            TextView smtext_state = (TextView) v.findViewById(R.id.smtext_state);
            Button btn_smtext = (Button) v.findViewById(R.id.btn_smtext);
            smtext.setText(lt.get(arg0).getCheckId());//"CK20201102100437  查库编号
            smtext_state.setText(lt.get(arg0).getReconciliationStr());
            btn_smtext.setText("显示进度");
            btn_smtext.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (lt.get(arg0).getReconciliationStr().equals("执行中")) {
                        Intent intent = new Intent(CKListInfoActivity.this, CkNotCompletedActivity.class);//  盘库代码
                        intent.putExtra("PKNO", lt.get(arg0).getCheckId());
                        Log.e(TAG, "-----" + lt.get(arg0).getCheckId());
                        startActivity(intent);
                    } else if (lt.get(arg0).getReconciliationStr().equals("待对账")) {
                        Intent intent = new Intent(CKListInfoActivity.this, CKReconcialationActivity.class);
                        intent.putExtra("PKNO", lt.get(arg0).getCheckId());
                        intent.putExtra("inventoy", lt.get(arg0).getInventoryNumber());
                        startActivity(intent);
                    }
                }
            });
            if (ltCurrent_Order.get(position).get(arg0) == 1) {
//                cbOrder.setChecked(true);
            } else {
//                cbOrder.setChecked(false);
            }

            return v;
        }

        class SelectListener implements CompoundButton.OnCheckedChangeListener {
            private int position;
            private int current;

            public SelectListener(int position, int current) {
                super();
                this.position = position;
                this.current = current;
            }

            @Override
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if (arg1) {
                    System.out.println("订单CheckBox设置为true");
                    ltCurrent_Order.get(position).set(current, 1);
                } else {
                    System.out.println("订单CheckBox设置为false");
                    ltCurrent_Order.get(position).set(current, 0);

                }
                System.out.println("test--" + ltCurrent_Order.toString());
                wa.notifyDataSetChanged();
                // updateAll();
            }
        }
    }

    String dataLibrary = "1";
    private String checkType = "2";// 查库  2 盘库
    private String Username = "";
    private String createresult;

    private void CreateTaskCK() {

        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    createresult = UpServer.addTask(checkType, dataLibrary, username, userid);

                    Log.e(TAG, "!!!!!!!!!!!!!!" + createresult);
                    if (createresult.equals("00")) {
                        handler.sendEmptyMessage(11);
                    } else {
                        handler.sendEmptyMessage(12);
                    }
                } catch (TimeoutException e) {
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//查无此人信息
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(2);//不是数字
                } catch (Exception e) {

                    e.printStackTrace();
                    Log.e("b", "异常" + e);
//                    Log.e("data报文加密失败！", e.getMessage());
                    handler.sendEmptyMessage(2);
                }
            }

        }.start();
    }


}
